package com.tsy.server.component.security;

import com.tsy.server.component.redis.RedisKeyConstant;
import com.tsy.server.common.util.JwtTokenUtil;
import com.tsy.server.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Value("${jwt.expiration}")
    private Long expiration;

    private static final String HEADER_NAME = "Sec-WebSocket-Protocol";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 获取请求头中的token
        String authHeader = request.getHeader(tokenHeader);
        String authToken;

        // 判断token是否存在且以Bearer开头
        if (authHeader != null && authHeader.startsWith(tokenHead)) {
            // 截取Bearer后的token
            authToken = authHeader.substring(tokenHead.length());
        } else {
            authToken = request.getHeader(HEADER_NAME);
        }

        if (StringUtils.hasText(authToken)) {
            // 从token中获取用户名
            String username = jwtTokenUtil.getUsernameFromToken(authToken);

            // 判断用户名是否存在且未认证
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 检查Redis中是否存在该token，实现单点登录控制
                String tokenKey = RedisKeyConstant.buildLoginTokenKey(authToken);
                if (redisUtil.hasKey(tokenKey)) {
                    // 加载用户信息
//                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    CustomUserDetails userDetails = (CustomUserDetails) redisUtil.get(tokenKey);
                    // 验证token是否有效
                    if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                        // 更新Redis中token的有效期（1天）
                        redisUtil.expire(tokenKey, expiration);
                        redisUtil.expire(RedisKeyConstant.buildUserTokenKey(username), expiration);
                        // 创建认证信息
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        // 设置认证信息到上下文
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                }
            }
        }
        // 继续执行过滤器链
        chain.doFilter(request, response);
    }
}